package cn.edu.jlu.grid.vjm;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class VJobStartMessage extends VJMMessage {
	/* the address of host on which the vjob starts */
	private InetAddress vjobAddress = null;
	
	/* when a vjob starts on a computional host, it will also establish
	 * a server socket for the use of receiving messages from
	 * vjm center
	 */
	private int vjobPort = -1;
	
	private int reservationId = -1;
	private int requestId = -1;
	
	public VJobStartMessage() {
	}
	public void onSend() {
		VJobExecute ve = VJobExecute.getInstance();
		vjobAddress = ve.getLocalAddress();
		vjobPort = ve.getLocalPort();
		reservationId = ve.getReservationHandler();
		requestId = ve.getRequestId();
	}

	public void onReceive(Socket connection) {
		VJob vjob = new VJob();
		vjob.setVjobMsgCenterAddress(vjobAddress);
		vjob.setVjobMsgCenterPort(vjobPort);
		VJobPool.getInstance().addVJob(reservationId, requestId, vjob);
		
		Socket socket = null;
		try {
			socket = new Socket(vjobAddress, vjobPort);
			ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
			os.writeObject(new VJobSetIdMessage(vjob.getId()));
			os.flush();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try { socket.close(); } catch (Exception e){}
		}
	}
	
	public String toString() {
		return "VJobStartMessage: vjobAddress : " + vjobAddress.getHostAddress() +
			" vjobPort: " + vjobPort + " reservationId: " +
			reservationId + " requestId: " + requestId;
	}
}
